package com.xiyou.week04.binaryReactor;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 239. 滑动窗口最大值
 *
 * @ClassName：MaxSlidingWindow
 * @Author：西柚
 * @Date：2022/1/7 3:19 下午
 * @Versiion：1.0
 */
public class MaxSlidingWindow {

    /**
     * 输入：nums = [1,3,-1,-3,5,3,6,7], k = 3
     * 输出：[3,3,5,5,6,7]
     * 解释：
     * 滑动窗口的位置                最大值
     * ---------------               -----
     * [1  3  -1] -3  5  3  6  7       3
     * 1 [3  -1  -3] 5  3  6  7       3
     * 1  3 [-1  -3  5] 3  6  7       5
     * 1  3  -1 [-3  5  3] 6  7       5
     * 1  3  -1  -3 [5  3  6] 7       6
     * 1  3  -1  -3  5 [3  6  7]      7
     * <p>
     *
     * @param nums
     * @param k
     * @return
     */
    public int[] maxSlidingWindow(int[] nums, int k) {
        Queue<int[]> q = new LinkedList<int[]>();
        int[] ans = new int[nums.length - k + 1];
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            q.add(new int[]{nums[i], i});
            if (i >= k - 1) {
                // [i-k+1, i] 这一段的max
                while (q.peek()[1] <= i - k) q.poll();
                ans[count] = q.peek()[0];
                count++;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};
        int k = 3;

        MaxSlidingWindow maxSlidingWindow = new MaxSlidingWindow();
        System.out.println(Arrays.toString(maxSlidingWindow.maxSlidingWindow(nums, k)));
    }
}
